package com.klikmee.sms.chat.web.usecases;

import java.util.ArrayList;

import com.dotexe.webframework.core.ClientApplication;
import com.dotexe.webframework.core.clientactions.MessageBox;
import com.dotexe.webframework.core.datasources.ObjectDataSource;
import com.dotexe.webframework.core.triggers.Trigger;
import com.klikmee.sms.chat.web.dao.AgentDAO;
import com.klikmee.sms.chat.web.dao.UserSession;
import com.klikmee.sms.chat.web.util.SpringBeansLookup;
import com.klikmee.sms.services.chat.model.Agent;

public class LoginForm extends ClientApplication {

	private ObjectDataSource dsLogin;
	private ArrayList<String> bcLogin;

	@Override
	public void load() throws Exception {
		super.load();
		this.dsLogin = new ObjectDataSource("dsLogin");
		this.getDataSources().add(dsLogin);

		this.triggers.add(new Trigger(this, "btnLoginClick"));

		this.bcLogin = new ArrayList<String>();
		this.bcLogin.add("AgentUserName");
		this.bcLogin.add("AgentPassword");
	}

	@Override
	public void start() throws Exception {
		super.start();

		Agent a = new Agent();
		this.dsLogin.setSource(a);
		this.dsLogin.bind(this.bcLogin);
	}

	public void btnLoginClick() throws InstantiationException,
			IllegalAccessException, Exception {

		AgentDAO agentDAO = SpringBeansLookup.getBean(AgentDAO.class);
		String userName = ((Agent) this.dsLogin.getSource()).getAgentUserName();
		String password = ((Agent) this.dsLogin.getSource()).getAgentPassword();

		if (userName != null && password != null) {
			Agent agent = agentDAO.login(userName.toString(),
					password.toString());
			if (agent != null) {
				// set current agent in session
				UserSession.setCurrentAgent(agent);
				// show main from
				MainForm main = this.createChildApplication(MainForm.class);
				this.showChildApp(main, "VIEWPORT");
				main.start();
				this.hide();
			} else {
				MessageBox.Show(this, "Obavestenje",
						"Uneti parametri nisu ispravni!");
				return;
			}
		} else {
			MessageBox.Show(this, "Obavestenje",
					"Uneti parametri nisu ispravni!");
			return;
		}
	}
}